package ee.maoinvest.frontend.controller.command.electricitycontractcommands;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ee.maoinvest.backend.model.data.ElectricityContract;
import ee.maoinvest.backend.services.ElectricityContractService;
import ee.maoinvest.backend.services.implementations.ElectricityContractServiceImpl;
import ee.maoinvest.frontend.controller.command.Command;
import ee.maoinvest.frontend.controller.formstringdataconverters.electricitycontractforms.EditElectricityContractFormConverter;
import ee.maoinvest.frontend.controller.requestprocessors.ElectricityContractFormsRequestProcessor;

public class FillEditElectricityContractFormConverterWithInitialDataCommand implements Command
{
	private int operationResult = 0;
	private final int OPERATION_SUCCESSFUL = 1;
	private final int EDITABLE_ELECTRICITY_CONTRACT_ID_PARSE_EXCEPTION_INDICATOR = -1;
	
	@Override
	public int executeCommand(HttpServletRequest request,
			HttpServletResponse response) 
	{
		ElectricityContractFormsRequestProcessor electricityContractFormsRequestProcessor = 
				new ElectricityContractFormsRequestProcessor();
		EditElectricityContractFormConverter editElectricityContractFormConverter = null;
		ElectricityContractService electricityContractServiceImpl = null;
		ElectricityContract electricityContractToEdit = null;
		
		int editableElectricityContractID = electricityContractFormsRequestProcessor.getEditableElectricityContractID(request);
		if (editableElectricityContractID != EDITABLE_ELECTRICITY_CONTRACT_ID_PARSE_EXCEPTION_INDICATOR)
		{
			electricityContractServiceImpl = new ElectricityContractServiceImpl();
			electricityContractToEdit = electricityContractServiceImpl.getElectricityContractById(editableElectricityContractID);
			
			if (electricityContractToEdit != null)
			{
				editElectricityContractFormConverter = new EditElectricityContractFormConverter();
				editElectricityContractFormConverter.fillWithInitialData(electricityContractToEdit);
				
				request.setAttribute("editElectricityContractFormConverter", editElectricityContractFormConverter);
				operationResult = OPERATION_SUCCESSFUL;
			}
		}
		
		return operationResult;
	}
}
